﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using spotnumbers.Model;

namespace spotnumbers.Controller
{
    /// <summary>
    /// Illustrate: separate between Game model and GameController
    /// </summary>
    public class GameController
    {
        public const int MaxNumber = 50;
        public const double Margin = 20;
        public const double Radius = 40;
        public const double SnapDistance = Radius;

        public Game Game { get; set; }
        public MainPage GamePage { get; set; }
        private List<Board> boards = new List<Board>();
        public Windows.UI.Xaml.Controls.TextBlock CurrentNumberView { get; set; }
        public GameController()
        {
            Game = new Game();
        }

        public void CreateGame(double boardWidth, double boardHeight)
        {
            Game.Numbers = NumberFactory.createNumbers(boardWidth, boardHeight, Margin, Radius, 2 * Radius, MaxNumber);
            Game.CurrentNumberIndex = 0;
            boards.Clear();
        }

        /// <returns>Returns true if the given location is closed to the current number </returns>
        private bool checkClickedLocation(double x, double y)
        {
            var game = Game;
            var currentNumberIndex = game.CurrentNumberIndex;

            if (currentNumberIndex < 0 || currentNumberIndex >= game.Numbers.Count)
                return false;

            var currentNumber = game.Numbers[game.CurrentNumberIndex];
            var distance = currentNumber.DistanceTo(x, y);
            
            return true;
            //return distance < SnapDistance;
        }

        public void PlayerClicked(double x, double y)
        {
            if (checkClickedLocation(x, y))
            {
                bool finish = !Game.NextNumber();
                Update();
            }
        }

        internal bool IsEnabled(Number number)
        {
            return Game.CurrentNumberIndex >= 0 && number.Id >= Game.CurrentNumberIndex;
        }


        internal void AddBoardView(Board board)
        {
            boards.Add(board);
        }

        internal void StartGame()
        {
            Update();
        }

        private void Update()
        {
            var index = Game.CurrentNumberIndex;
            if (index < 0)
                CurrentNumberView.Text = "Ready";
            else if (index >= Game.Numbers.Count)
                GamePage.ShowWinner();
            else
                CurrentNumberView.Text = Game.Numbers[Game.CurrentNumberIndex].Text;
            UpdateAllBoards();
        }

        private void UpdateAllBoards()
        {
            foreach (var board in boards)
                board.Update();
        }
    }
}
